﻿using System.Data.SqlClient;
using System.Transactions;
using System.Web;

namespace Skyhook.TransactionControl.Objects {
    public class DataAccess {
        public static SqlConnection GetConnection() {
            if (HttpContext.Current != null && HttpContext.Current.Session != null)
                if (HttpContext.Current.Session["SqlConnection"] != null)
                    return (SqlConnection)HttpContext.Current.Session["SqlConnection"];
                else {
                    var connection = GetNewConnection();
                    HttpContext.Current.Session["SqlConnection"] = connection;
                    return connection;
                }
            else {
                if (SqlConnectionLocal.Connection != null)
                    return SqlConnectionLocal.Connection;
                else {
                    var connection = GetNewConnection();
                    SqlConnectionLocal.Connection = connection;
                    return connection;
                }
            }
        }

        private static SqlConnection GetNewConnection() {
            var transaction = TransactionManager.Get();

            var connection = new SqlConnection("server=(local)\\SQLExpress;Integrated Security=SSPI;database=northwind");
            connection.Open();
            connection.EnlistTransaction(transaction);
            return connection;
        }

        public static SqlCommand CreateCommand() {
            var connection = GetConnection();
            var command = new SqlCommand { Connection = connection };

            return command;
        }
    }
    internal static class SqlConnectionLocal {
        public static SqlConnection Connection;
    }
    public static class DataAccessExtensions {
        public static void Execute(this SqlCommand command) {
            command.ExecuteNonQuery();
        }
    }
}